package com.example.cc.mygit.view.login;

import android.text.TextUtils;

import com.example.cc.mygit.R;
import com.example.cc.mygit.model.User;
import com.example.cc.mygit.source.API;
import com.haibin.elegant.Response;
import com.haibin.elegant.call.CallBack;

import java.util.regex.Pattern;

/**
 * Created by cc on 2016/11/13.
 */

public class LoginPresenter implements LoginContract.Presenter {
    private final LoginContract.View mView;

    public LoginPresenter(LoginContract.View mView) {
        this.mView = mView;
        this.mView.setPresenter(this);
    }

    @Override
    public void login(String email, String pwd) {
        if (!checkEmail(email)){
            mView.showEmailError(R.string.email_error);
            return;
        }
        if (TextUtils.isEmpty(pwd)){
            mView.showPasswordEmptyError(R.string.password_empty_error);
            return;
        }

        API.login(email, pwd, new CallBack<User>() {
            @Override
            public void onResponse(Response<User> response) {
                User user = response.getBody();
                if (user !=null){
                    mView.showLoginSuccess(R.string.login_success,user);
                }else{
                    mView.showLoginError(R.string.login_error);
                }
            }

            @Override
            public void onFailure(Exception e) {
                mView.showNetError(R.string.login_error);

            }
        });

    }

    @Override
    public void register() {

    }

    @Override
    public void rememberPassword() {

    }

    @Override
    public void start() {

    }
    private boolean checkEmail(String email){
        if (TextUtils.isEmpty(email))
            return false;
        Pattern pattern = Pattern.compile("\\w+@\\w+\\.(com|cn)");
        if (pattern.matcher(email).find())
            return true;
        return false;
    }
}
